import bus from "../../utils/bus";
import Datafeeds from "./datafeed";

// 处理websocket返回的数据
const websocketGetData = (params) => {
  let {data,that,onErrorCallback } = params;
  var paramArr  = [data.klineType,data.symbolInfo.ticker];
  bus.$emit("websocket_publicTradingView_start",paramArr)
  bus.$on('reconnectTradingView',function () {
    reconnectWebsocket(data.symbolInfo,data.klineType,that,onErrorCallback);
  });
  bus.$on("dealGetWebsocketData",function(binaryData){
    console.log("=============="+binaryData)
    if(!binaryData){
      return;
    }
    dealWebsocekSuccess(binaryData,that);
  })
};
const offerWebsocket = (oldParams) => {
  let {data} = oldParams;
  bus.$off("reconnectTradingView");
  bus.$off("dealGetWebsocketData");
  // bus.$off("websocket_publicTradingView_start");
  bus.$emit('websocket_publicTradingView_stop',data);
}
const dealWebsocekSuccess = (binaryData,that) => {
  const dataList = convertWebsocketData(binaryData);
  if(dataList && dataList.length > 0){
    var length=dataList.length-1;
    for(let i=0;i<length+1;i++){
      let pushData = dataList[i];
      if(Number(pushData.time)>=Datafeeds.lastKlineTime) {
        that.onRealtimeCallback(dataList[i]);
        that.lastKlineTime=dataList[length].time;
      }
    }
  }
};
const reconnectWebsocket = (symbolInfo,klineType,that,onErrorCallback)=>{
  var param = {
    symbolId: symbolInfo.ticker,
    from: that.lastKlineTime,
    type: klineType
  };

  that._send(that.request, param)
    .done((res) => {
      if(res.data && res.data.length>0){
        const klineData = res.data;
        const length = klineData.length;
        for(let i=0; i<length; i++){
          const pushData = klineData[i];
          if(Number(pushData.time) >= that.lastKlineTime) {
            that.onRealtimeCallback(klineData[i]);
            that.lastKlineTime=klineData[length-1].time;
          }
        }

      }
      const paramArr = [klineType,symbolInfo.ticker];
      bus.$emit("websocket_publicTradingView_start",paramArr)
    })
    .fail((arg) => {
      if (onErrorCallback) {
        onErrorCallback(`network error: ${JSON.stringify(arg)}`);
      }
    });
}

const filteringTime = (resolution) => {
  let klineType = "1min";
  if (resolution == 1) {
    klineType = "1min";
  } else if (resolution == 5) {
    klineType = "5min";
  } else if (resolution == 15) {
    klineType = "15min";
  } else if (resolution == 30) {
    klineType = "30min";
  } else if (resolution == 60) {
    klineType = "60min";
  } else if(resolution == 240) {
    klineType = "4hour";
  } else if (resolution == "1D") {
    klineType = "1day";
  } else if (resolution == "1W") {
    klineType = "1week";
  }
  return klineType
};
const converResolutionToType = (resolution) => {
  let klineType = 0;
  if (resolution == 1) {
    klineType = 0;
  } else if (resolution == 5) {
    klineType = 1;
  } else if (resolution == 15) {
    klineType = 2;
  } else if (resolution == 30) {
    klineType = 9;
  } else if (resolution == 60) {
    klineType = 10;
  } else if(resolution == 240){
    klineType = 12;
  } else if (resolution == "1D") {
    klineType = 3;
  } else if (resolution == "1W") {
    klineType = 4;
  }
  return klineType;
}
const transformTime = (time) => {
  let period = '';
  if (time.indexOf('D') !== -1 || time.indexOf('W') !== -1 || time.indexOf('M') !== -1) {
    period = time;
  } else if (parseInt(time) < 60) {
    period = `${time}min`;
  } else if (parseInt(time) <= 720) {
    const hourNumber = Math.floor(parseInt(time) / 60);
    period = `${hourNumber}hour`;
  }

  return period;
};

var reversalData = (dataList) => {
  if(dataList && dataList.length > 0){
    var converList = [];
    var dataLength=dataList.length;
    for (var i = dataLength-1; i >=0; i--) {
      converList.push(dataList[i]);
    }
    return converList;
  }
  return null;
}
const convertWebsocketData = (dataList)=> {
  if (!dataList || !(dataList instanceof Array)) {
    return null;
  }
  var converList = [];
  for (let i = 0; i < dataList.length; i++) {
    var data = dataList[i];
    var converdate = {time: data[0], close: Number(data[4]), open: Number(data[1]), high: Number(data[2]), low: Number(data[3]), volume: Number(data[5])};
    converList.push(converdate);
  }
  return converList;
}

const volume_precision = (info_precision) => {
  if (!info_precision) {
    info_precision = 8;
  }
  info_precision = parseInt(info_precision);
  let scale = 1;
  for (let i = 0; i < info_precision; i++) {
    scale = scale * 10;
  }
  return scale;
}

export default {
  volume_precision,
  offerWebsocket,
  websocketGetData,
  convertWebsocketData,
  reversalData,
  filteringTime,
  transformTime,
  converResolutionToType
};
